"""
分类相关视图
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view

from pecco_site.models import Category
from ..serializers.category import CategoryListSerializer, CategoryDetailSerializer
from ..filters import CategoryFilter
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取分类列表', tags=['分类管理']),
    retrieve=extend_schema(summary='获取分类详情', tags=['分类管理']),
    create=extend_schema(summary='创建分类', tags=['分类管理']),
    update=extend_schema(summary='更新分类', tags=['分类管理']),
    partial_update=extend_schema(summary='部分更新分类', tags=['分类管理']),
    destroy=extend_schema(summary='删除分类', tags=['分类管理']),
)
class CategoryViewSet(viewsets.ModelViewSet):
    """分类管理 ViewSet"""
    queryset = Category.objects.all().prefetch_related('translations')
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = CategoryFilter
    search_fields = ['slug', 'translations__name']
    ordering_fields = ['sort_order', 'created_at', 'updated_at']
    ordering = ['sort_order', 'slug']

    def get_serializer_class(self):
        if self.action == 'list':
            return CategoryListSerializer
        return CategoryDetailSerializer

    @extend_schema(summary='切换分类激活状态', tags=['分类管理'])
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换分类激活状态"""
        category = self.get_object()
        category.is_active = not category.is_active
        category.save()
        return Response({'is_active': category.is_active})

